import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/group_api.dart';
import 'package:sainbainu/common/models/request/pager_request.dart';
import 'package:sainbainu/common/models/response/group_list_response.dart';
import 'package:sainbainu/common/repositories/group_repository.dart';
import 'package:sainbainu/common/routes/routes.dart';

import 'index.dart';

class MyGroupsController extends GetxController {
  MyGroupsController();

  final state = MyGroupsState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    state.refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: false,
    );
    state.groupRepository = GroupRepository(GroupApi());

    getMyGroupList();
    getJoinGroupList();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.refreshController.dispose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  /// 我建立的小组
  Future getMyGroupList() async {
    var res = await state.groupRepository.myList(
      PagerRequest(pageSize: 20),
      creatorFlag: 1,
    );
    state.myGroupListResponse = res;
    update(['myGroupList']);
  }

  /// 我加入的小组
  Future getJoinGroupList() async {
    var res = await state.groupRepository.myList(
      PagerRequest(pageSize: 20),
      creatorFlag: 0,
    );
    state.joinGroupListResponse = res;
    update(['joinGroupList']);
  }

  /// 下拉刷新
  Future onRefresh() async {
    try {
      await getMyGroupList();
      await getJoinGroupList();
      state.refreshController.finishRefresh(IndicatorResult.success);
    } catch (e) {
      state.refreshController.finishRefresh(IndicatorResult.fail);
    }
  }

  /// 小组详情页
  toGroupDetailPage(CroupItemResponse item) {
    Get.toNamed(
      AppRoutes.groupDetail,
      arguments: {
        'groupId': item.groupId,
        'uniqueTag': item.uniqueTag,
        'cover': item.cover,
      },
    );
  }
}
